package com.os.opencv.java.chapter9;

import org.opencv.core.*;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.util.ArrayList;
import java.util.List;

public class FindContours {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        //读取图像并在屏幕上显示
        Mat src = Imgcodecs.imread("/Users/matt/Pictures/111.jpg", Imgcodecs.IMREAD_GRAYSCALE);
        HighGui.imshow("wanlifuwangshi", src);
        HighGui.waitKey(0);

        Mat binary = new Mat();
        Imgproc.threshold(src, binary, 90, 255, Imgproc.THRESH_BINARY);
        HighGui.imshow("binary", binary);
        HighGui.waitKey(0);

        //根据而知图检测轮廓
        List<MatOfPoint> contours = new ArrayList<>();
        Imgproc.findContours(binary, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

        //画出轮廓图并在屏幕上显示
        Mat imgBinary = new Mat(src.height(), src.width(), CvType.CV_8UC3, new Scalar(255, 255, 255));
        for(int i=0; i<contours.size(); i++)
            Imgproc.drawContours(imgBinary, contours, i, new Scalar(0,0,0), 1);

        HighGui.imshow("contours from binary", imgBinary);
        HighGui.waitKey(0);

        //进行canny检测并在屏幕上显示
        Mat canny = new Mat();
        Imgproc.Canny(src, canny, 60, 200);
        HighGui.imshow("canny", canny);
        HighGui.waitKey(0);

        //根据canny结果检测轮廓
        List<MatOfPoint> contour2 = new ArrayList<>();
        Imgproc.findContours(canny, contour2, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

        //画出轮廓并在屏幕上显示
        Mat imgCanny = new Mat(src.height(), src.width(), CvType.CV_8UC3, new Scalar(255,255,255));
        for(int i=0; i<contour2.size(); i++){
            Imgproc.drawContours(imgCanny, contour2, i, new Scalar(0,0,0), 1);
        }
        HighGui.imshow("contours from canny", imgCanny);
        HighGui.waitKey(0);

        System.exit(0);
    }
}
